package com.ishanggang.service;

import com.ishanggang.entity.IsgStore;
import com.ishanggang.entity.JddjStore;
import com.ishanggang.mapper.IsgStoreMapper;
import com.ishanggang.mapper.JddjStoreMapper;
import com.ishanggang.util.GaoDeLatAndLngUtil;
import com.ishanggang.util.GeoHashUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;

import static com.ishanggang.service.BrandMatchJddjStoreService.*;

@Service
public class IShangGangMatchJddjStoreService {

    private static final Logger logger = LoggerFactory.getLogger(IShangGangMatchJddjStoreService.class);

    @Autowired
    private IsgStoreMapper isgStoreMapper;

    @Resource
    private JddjStoreMapper jddjStoreMapper;

    @Resource
    private GeoHashUtil geoHashUtil;

    // 距离总分为20分
    private static final Integer DISTANCE_TOTAL_SCORE = 15;
    // 距离每增加 100 M,匹配度得分扣 N 目前设置为5
    private static final Integer DISTANCE_PER_HUNDRED_M_SCORE = 3;
    // 门店 零售商名称 每匹配一个字,加 6 分
    private static final Integer RETAIL_VENDOR_NAME_PER_WORD_MATCH_SCORE = 6;
    // 门店 零售商集团名称 每匹配一个字,加 4 分
    private static final Integer RETAIL_VENDOR_GROUP_NAME_PER_WORD_MATCH_SCORE = 4;

    public void updateShopLongLat() {
        // 取最大id
        Long maxId = this.isgStoreMapper.selectMaxId();
        Long i = 1L;
        while (true) {
            try {
                IsgStore isgStore = this.isgStoreMapper.selectById(i);
                if (isgStore != null && !StringUtils.isEmpty(isgStore.getAddress())) {
                    Map<String, String> queChaoBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag((String) isgStore.getAddress());
                    if (!CollectionUtils.isEmpty(queChaoBaiduLatAndLngMap)) {
                        this.isgStoreMapper.updateShopLongLat(i, Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lng")), Double.parseDouble((String) queChaoBaiduLatAndLngMap.get("lat")));
                        logger.info("门店id:{},门店名称:{}--距离偏差值为{}m", isgStore.getId(), isgStore.getIsgShopName(), 1);
                    } else {
//            this.shopQuechaoMapper.updateShopLongLatAddressDistance(i, Double.parseDouble("-1"));
                        logger.error("门店id:{},门店名称:{}--经纬度查询不合法{}", isgStore.getId(), isgStore.getIsgShopName(), queChaoBaiduLatAndLngMap);
                    }
                }
            } catch (Exception e) {
                logger.error("门店经纬度与地址不准统计，门店id:{}", i, e);
            }
            if (i > maxId) {
                break;
            }
            i++;
        }
    }

    /**
     * 将爱上岗的门店信息与到家门店信息进行匹配
     */
    public void buildIShangGangShopMatchJDDJStoreAll() {
        Long maxId = this.isgStoreMapper.selectMaxId();
        Long i = 1L;
        while (true) {
            try{
                this.buildIShangGangShopMatchJDDJStoreItem(i);
            } catch (Exception e) {
                logger.error("门店id-{}", i, e);
            }
            if (i > maxId) {
                break;
            }
            i++;
        }
    }

    /**
     * 单门店匹配逻辑
     *
     * @param storeId 主键id
     */
    private void buildIShangGangShopMatchJDDJStoreItem(Long storeId) {
        IsgStore isgStore = this.isgStoreMapper.selectById(storeId);
        if (isgStore != null) {
            // 艾维斯门店经纬度
            double brandShopLng = Double.parseDouble(isgStore.getLongitude());
            double brandShopLat = Double.parseDouble(isgStore.getLatitude());

            // 查询门店附近的到家门店列表
            GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = this.geoHashUtil.redisNearByXY(JDDJ_STORE_GEOHASH_KEY, brandShopLng, brandShopLat, DISTANCE, totalCount);

            //遍历附近的到家门店 - 找到打分最高，匹配度最高的门店
            int matchType = 0; // 匹配类型 1. vender_equal 零售商精准匹配 2. vender_like 零售商模糊匹配 3. near_by 距离匹配 精度最差
            int matchScore = 0; // 分数
            JddjStore bestJDDJStore = null;
            String scoreDetailStr = null; // 计算过程
            for (GeoResult<RedisGeoCommands.GeoLocation<String>> item : geoResults.getContent()) {
                // 计算的详细过程
                StringBuilder scoreDetailBuilder = new StringBuilder();
                // 艾维斯门店名称
                String isgShopName = isgStore.getIsgShopName();
                JddjStore jddjStore = this.jddjStoreMapper.selectById(Long.parseLong(String.valueOf(item.getContent().getName())));
                int itemMatchType = 0;
                if (jddjStore != null) {
                    // 1.零售商子公司匹配
                    String jddjStoreVendorName = jddjStore.getVenderName();
                    StringBuilder matchRetailVenderName = new StringBuilder();
                    if (!StringUtils.isEmpty(isgShopName) && !StringUtils.isEmpty(jddjStoreVendorName)) {
                        for (int j = 0; j < jddjStoreVendorName.length(); j++) {
                            if (isgShopName.contains(String.valueOf(jddjStoreVendorName.charAt(j)))) {
                                matchRetailVenderName.append(jddjStoreVendorName.charAt(j));
                            }
                        }
                    }
                    int jddjStoreVendorNameMatchScore = matchRetailVenderName.length() * RETAIL_VENDOR_NAME_PER_WORD_MATCH_SCORE;
                    if (matchRetailVenderName.length() < 3) {
                        jddjStoreVendorNameMatchScore = 0;
                    }
                    itemMatchType = 1;
                    scoreDetailBuilder.append("商家匹配文本:" + matchRetailVenderName + "-得分:" + jddjStoreVendorNameMatchScore + ";/n");
                    // 2.零售商集团名称匹配
                    String jddjStoreVendorGroupName = jddjStore.getVenderGroupName();
                    StringBuilder matchRetailVendorGroupName = new StringBuilder();
                    if (!StringUtils.isEmpty(isgShopName) && !StringUtils.isEmpty(jddjStoreVendorGroupName)) {
                        for (int j = 0; j < jddjStoreVendorGroupName.length(); j++) {
                            if (isgShopName.contains(String.valueOf(jddjStoreVendorGroupName.charAt(j)))) {
                                matchRetailVendorGroupName.append(jddjStoreVendorGroupName.charAt(j));
                            }
                        }
                    }
                    int jddjStoreVendorGroupNameMatchScore = matchRetailVendorGroupName.length() * RETAIL_VENDOR_GROUP_NAME_PER_WORD_MATCH_SCORE;
                    if (matchRetailVendorGroupName.length() < 3) {
                        jddjStoreVendorGroupNameMatchScore = 0;
                    }
                    if (jddjStoreVendorGroupNameMatchScore > jddjStoreVendorNameMatchScore) {
                        itemMatchType = 2;
                    }
                    scoreDetailBuilder.append("商家集团匹配文本:" + matchRetailVendorGroupName + "-得分:" + jddjStoreVendorGroupNameMatchScore + ";/n");

                    // 3.距离打分 商家和门店匹配距离 总分50分  每差100米 减 n分，最低0分.
                    StringBuilder matchDistanceBuilder = new StringBuilder();
                    BigDecimal b1 = new BigDecimal(item.getDistance().getValue());
                    int distanceScore = DISTANCE_TOTAL_SCORE - b1.multiply(BigDecimal.valueOf(10)).intValue() * DISTANCE_PER_HUNDRED_M_SCORE;
                    distanceScore = Math.max(distanceScore, 0);
                    matchDistanceBuilder.append("相距距离满分50分-真实距离：" + item.getDistance().getValue() + "KM，每100米减" + DISTANCE_PER_HUNDRED_M_SCORE + ",得" + distanceScore + "分;---");
                    scoreDetailBuilder.append("门店距离匹配:" + b1 + "-得分:" + distanceScore + ";/n");
                    if ( distanceScore> jddjStoreVendorGroupNameMatchScore) {
                        itemMatchType = 3;
                    }


                    int totalScore = jddjStoreVendorNameMatchScore + jddjStoreVendorGroupNameMatchScore + distanceScore;
                    logger.info("爱上岗门店名称{}-到家门店名称{}-匹配得分:{}-匹配过程:{}", isgShopName, jddjStore.getShopName(), totalScore, scoreDetailBuilder);
                    if (totalScore > matchScore) {
                        matchScore = totalScore;
                        matchType = itemMatchType;
                        scoreDetailStr = scoreDetailBuilder.toString();
                        bestJDDJStore = jddjStore;
                    }
                }
            }
            if (matchScore > 0 && !Objects.isNull(bestJDDJStore)) {
                logger.error("爱上岗门店名称{}-到家门店名称{}-匹配类型:{}-匹配得分:{}-匹配过程:{}", isgStore.getIsgShopName(), bestJDDJStore.getShopName(),matchType, matchScore, scoreDetailStr);
                isgStoreMapper.updateMatchJDDJShopInfo(isgStore.getId(), bestJDDJStore.getShopId(),
                        bestJDDJStore.getVenderId(), bestJDDJStore.getVenderName(),
                        bestJDDJStore.getVenderGroupId(), bestJDDJStore.getVenderGroupName(),
                        bestJDDJStore.getShopName(), matchType, matchScore, scoreDetailStr);
            }
        }
    }
}
